package com.ruoyi.study.controller;
import com.google.common.collect.Maps;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.disk.domain.DiskFile;
import com.ruoyi.disk.service.IDiskFileService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.studylog.domain.UserStudyLog;
import com.ruoyi.studylog.service.IUserStudyLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.study.domain.UserStudyDetail;
import com.ruoyi.study.service.IUserStudyDetailService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学习记录明细Controller
 * 
 * @author ruoyi
 * @date 2024-12-05
 */
@RestController
@RequestMapping("/study/detail")
@Api("学习记录明细")
public class UserStudyDetailController extends BaseController
{
    @Autowired
    private IUserStudyDetailService userStudyDetailService;
    @Autowired
    private IDiskFileService diskFileService;

    @Autowired
    private IUserStudyLogService logService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询学习记录明细列表
     */
    @PreAuthorize("@ss.hasPermi('study:detail:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserStudyDetail userStudyDetail)
    {
        startPage();
        List<UserStudyDetail> list = userStudyDetailService.selectUserStudyDetailList(userStudyDetail);
        return getDataTable(list);
    }

    @GetMapping("/heartBeat")
    @ApiOperation("学习记录心跳")
    public AjaxResult heartBeat(@RequestParam Long fileId)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        if (ObjectUtil.isNull(user)) {
            throw new RuntimeException("查询不到该用户");
        }
        DiskFile diskFile = diskFileService.selectDiskFileById(fileId);
        if (ObjectUtil.isNull(diskFile)){
            throw new RuntimeException("查询不到文件信息");
        }
        Object cacheObject = redisCache.getCacheObject("study:" + user.getUserId()+fileId);
        if (ObjectUtil.isNull(cacheObject)){
            UserStudyLog userStudyLog = new UserStudyLog();
            userStudyLog.setUserId(user.getUserId());
            userStudyLog.setFileId(fileId);
            userStudyLog.setTotalTime(0L);
            userStudyLog.setDeptId(userStudyLog.getDeptId());
            userStudyLog.setCreateBy(user.getUserId()+"");
            userStudyLog.setCreateTime(new Date());
            userStudyLog.setUpdateBy(user.getUserId()+"");
            userStudyLog.setUpdateTime(new Date());
            logService.insertUserStudyLog(userStudyLog);



            UserStudyDetail userStudyDetail=new UserStudyDetail();
            userStudyDetail.setUserId(user.getUserId());
            userStudyDetail.setFileId(fileId);
            userStudyDetail.setDuration(1L);
            userStudyDetail.setDeptId(userStudyDetail.getDeptId());
            userStudyDetail.setCreateBy(user.getUserId()+"");
            userStudyDetail.setCreateTime(new Date());
            userStudyDetail.setUpdateBy(user.getUserId()+"");
            userStudyDetail.setUpdateTime(new Date());
            userStudyDetail.setLogId(userStudyLog.getId());
            userStudyDetailService.insertUserStudyDetail( userStudyDetail);


            //todo websocket通知用户开始学习文件

            redisCache.setCacheObject("study:" + user.getUserId()+fileId, userStudyLog.getId(),5, TimeUnit.MINUTES);
        }else {
            UserStudyLog userStudyLog = logService.selectUserStudyLogById((Long) cacheObject);
            if (ObjectUtil.isNull(userStudyLog)){
                throw new RuntimeException("查询不到学习记录");
            }
            UserStudyDetail userStudyDetail=new UserStudyDetail();
            userStudyDetail.setUserId(user.getUserId());
            userStudyDetail.setFileId(fileId);
            userStudyDetail.setDuration(1L);
            userStudyDetail.setDeptId(userStudyDetail.getDeptId());
            userStudyDetail.setCreateBy(user.getUserId()+"");
            userStudyDetail.setCreateTime(new Date());
            userStudyDetail.setUpdateBy(user.getUserId()+"");
            userStudyDetail.setUpdateTime(new Date());
            userStudyDetail.setLogId(userStudyLog.getId());
            userStudyDetailService.insertUserStudyDetail( userStudyDetail);

            userStudyLog.setTotalTime(userStudyLog.getTotalTime()+1);
            userStudyLog.setUpdateTime(new Date());
            logService.updateUserStudyLog(userStudyLog);

        }

        return AjaxResult.success("success");
    }
    /**
     * 导出学习记录明细列表
     */
    @PreAuthorize("@ss.hasPermi('study:detail:export')")
    @Log(title = "学习记录明细", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(UserStudyDetail userStudyDetail)
    {
        List<UserStudyDetail> list = userStudyDetailService.selectUserStudyDetailList(userStudyDetail);
        ExcelUtil<UserStudyDetail> util = new ExcelUtil<UserStudyDetail>(UserStudyDetail.class);
        return util.exportExcel(list, "学习记录明细数据");
    }

    /**
     * 获取学习记录明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('study:detail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(userStudyDetailService.selectUserStudyDetailById(id));
    }

    /**
     * 新增学习记录明细
     */
    @PreAuthorize("@ss.hasPermi('study:detail:add')")
    @Log(title = "学习记录明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserStudyDetail userStudyDetail)
    {
        return toAjax(userStudyDetailService.insertUserStudyDetail(userStudyDetail));
    }

    /**
     * 修改学习记录明细
     */
    @PreAuthorize("@ss.hasPermi('study:detail:edit')")
    @Log(title = "学习记录明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserStudyDetail userStudyDetail)
    {
        return toAjax(userStudyDetailService.updateUserStudyDetail(userStudyDetail));
    }

    /**
     * 删除学习记录明细
     */
    @PreAuthorize("@ss.hasPermi('study:detail:remove')")
    @Log(title = "学习记录明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userStudyDetailService.deleteUserStudyDetailByIds(ids));
    }
}
